/**
 * Description: 
 * version: 1.0
 * Author: Zero
 * Date: 2021-10-21 00:35:23
 * LastEditors: Zero
 * LastEditTime: 2021-10-24 17:03:53
 */
#include "Lib_74HC595.h"

#include "esp32/rom/ets_sys.h"

#define SRCLK_H gpio_set_level(SRCLK_PIN, 1)
#define SRCLK_L gpio_set_level(SRCLK_PIN, 0)
#define RCLK_H gpio_set_level(RCLK_PIN, 1)
#define RCLK_L gpio_set_level(RCLK_PIN, 0)
#define DATA_H gpio_set_level(DATA_PIN, 1)
#define DATA_L gpio_set_level(DATA_PIN, 0)

void HC595LibInit(void)
{
      //zero-initialize the config structure.
    gpio_config_t io_conf = {};
    //disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_OUTPUT;
    //bit mask of the pins that you want to set,e.g.GPIO18/19
    io_conf.pin_bit_mask = SRCLK_PIN_SEL | RCLK_PIN_SEL | DATA_PIN_SEL;
    //disable pull-down mode
    io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
    //disable pull-up mode
    io_conf.pull_up_en = GPIO_PULLDOWN_ENABLE;
    //configure GPIO with the given settings
    gpio_config(&io_conf);
}

void Hc595SendByte(unsigned char dat)
{
    unsigned char i = 0;
	
	for (i=0;i<8;i++)
	{
        if ((dat<<i) & 0x80) 
        DATA_H;
        else
        DATA_L;

        SRCLK_L;
        ets_delay_us (1);
        SRCLK_H;	
	}
    RCLK_L ;
    ets_delay_us (1);
    RCLK_H;
    ets_delay_us (1);
    RCLK_L;
    ets_delay_us (1);
}

void Hc595DisplayFrame(unsigned char pDat[])
{
    for (size_t i = 0; i < 6; i++)
    {
        Hc595SendByte(pDat[i]);
    }
}

void Hc595DisplayNum(unsigned char pDat[])
{
    unsigned char i,Nnow[6];

    for (i = 0; i < 6; i++)
    {
        switch (*(pDat + i))
        {
            // for ESP32
            case  0: Nnow[i] = 0x09; break;           //0
            case  1: Nnow[i] = 0x7D; break;			//1
            case  2: Nnow[i] = 0x91; break;			//2
            case  3: Nnow[i] = 0x31; break;			//3
            case  4: Nnow[i] = 0x65; break;			//4
            case  5: Nnow[i] = 0x23; break;			//5
            case  6: Nnow[i] = 0x03; break;			//6
            case  7: Nnow[i] = 0x79; break;			//7
            case  8: Nnow[i] = 0x01; break;			//8
            case  9: Nnow[i] = 0x21; break;			//9						
        } 
        Hc595SendByte(Nnow[i]);
    }
}
